# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


class CpqProject(models.Model):
    """项目主表 - 管理成本核算项目"""
    _name = 'cpq.project'
    _description = '成本核算项目'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc, id desc'

    # 基本信息
    name = fields.Char(
        string='项目名称',
        required=True,
        tracking=True,
        help='如: MS11项目、T167项目'
    )
    code = fields.Char(
        string='项目编号',
        required=True,
        copy=False,
        default=lambda self: _('New'),
        tracking=True
    )
    customer_id = fields.Many2one(
        'res.partner',
        string='客户',
        required=True,
        tracking=True,
        domain=[('is_company', '=', True)]
    )
    end_customer = fields.Char(
        string='最终客户(OEM)',
        tracking=True,
        help='如: 奔驰、宝马、小米'
    )
    vehicle_model = fields.Char(
        string='车型',
        tracking=True,
        help='如: E级W214'
    )
    
    # 项目状态
    state = fields.Selection([
        ('draft', '草稿'),
        ('l1', 'L1初版'),
        ('l2', 'L2竞标锁定'),
        ('l3', 'L3 SOP'),
        ('done', '完成'),
        ('cancelled', '取消')
    ], string='状态', default='draft', required=True, tracking=True)
    
    # 产量信息
    estimated_quantity = fields.Float(
        string='预计总产量',
        tracking=True,
        help='整个项目生命周期的预计产量'
    )
    annual_quantity = fields.Float(
        string='年度产量',
        tracking=True
    )
    lifecycle_years = fields.Float(
        string='项目生命周期(年)',
        default=5,
        tracking=True
    )
    sop_date = fields.Date(
        string='SOP日期',
        tracking=True,
        help='Start of Production'
    )
    
    # 关联数据
    bom_ids = fields.One2many(
        'cpq.bom',
        'project_id',
        string='BOM版本'
    )
    bom_count = fields.Integer(
        string='BOM版本数',
        compute='_compute_bom_count'
    )
    
    # 当前活动版本
    current_bom_id = fields.Many2one(
        'cpq.bom',
        string='当前BOM版本',
        help='当前激活的BOM版本'
    )
    
    # 负责人
    user_id = fields.Many2one(
        'res.users',
        string='成本负责人',
        default=lambda self: self.env.user,
        tracking=True
    )
    
    # 备注
    description = fields.Text(string='项目描述')
    notes = fields.Html(string='备注')
    
    # 公司
    company_id = fields.Many2one(
        'res.company',
        string='公司',
        required=True,
        default=lambda self: self.env.company
    )
    
    @api.model
    def create(self, vals):
        """创建项目时自动生成编号"""
        if vals.get('code', _('New')) == _('New'):
            vals['code'] = self.env['ir.sequence'].next_by_code('cpq.project') or _('New')
        return super().create(vals)
    
    def _compute_bom_count(self):
        """计算BOM版本数量"""
        for project in self:
            project.bom_count = len(project.bom_ids)
    
    def action_view_boms(self):
        """查看项目的所有BOM版本"""
        self.ensure_one()
        return {
            'name': _('BOM版本'),
            'type': 'ir.actions.act_window',
            'res_model': 'cpq.bom',
            'view_mode': 'list,form',
            'domain': [('project_id', '=', self.id)],
            'context': {'default_project_id': self.id}
        }
    
    def action_import_bom(self):
        """打开BOM导入向导"""
        self.ensure_one()
        return {
            'name': _('导入BOM'),
            'type': 'ir.actions.act_window',
            'res_model': 'cpq.bom.import.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {'default_project_id': self.id}
        }
